import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';
import printJS from 'print-js';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { getAddressNameByCode, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Button,
  DatePicker,
  Descriptions,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import { DetailInfoItem, TableListItem } from './data';
import PrintCount from './components/PrintCount';
import CountDetail from './components/CountDetail';

const { RangePicker } = DatePicker;
const { Item } = Descriptions;
const defaultData = new Date().toLocaleDateString();

interface CountProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  detailInfo: DetailInfoItem;
  dataInfo: DetailInfoItem;
  location: { query: any };
  detailCountInfo: DetailInfoItem;
}

interface CountState {
  pageIndex: number;
  pageSize: number;
  detailVisible: boolean;
  startDate: string;
  endDate: string;
  href: string;
  rowId:number;
}

function mapStateToProps(state: any) {
  const {
    VIPUserManagementCount: {
      detailInfo, dataInfo, loading, detailCountInfo,
    },
  } = state;
  return {
    detailInfo,
    dataInfo,
    loading,
    detailCountInfo,
  };
}

@connect(mapStateToProps)
class CountElem extends Component<CountProps, CountState> {
  columns = [
    { title: '日期', dataIndex: 'date' },
    { title: '揽件数', dataIndex: 'count' },
    {
      title: '揽件金额（元）',
      dataIndex: 'money',
      render: (text: number) => (text ? (text / 100).toFixed(2) : '0.00'),
    },
    {
      title: '现金支付（元）',
      dataIndex: 'spotPayment',
      render: (text: number) => (text ? (text / 100).toFixed(2) : '0.00'),
    },
    {
      title: '月结支付（元）',
      dataIndex: 'monthMoney',
      render: (text: number) => (text ? (text / 100).toFixed(2) : '0.00'),
    },
    {
      title: '操作',
      render: (text: any, record: any) => (
        <div>
          <span className="operLink" onClick={() => this.handleShowDetail(true, record)}>
            查看明细
          </span>
        </div>
      ),
    },
  ];

  state: CountState = {
    pageIndex: 1,
    pageSize: 20,
    detailVisible: false,
    startDate: defaultData,
    endDate: defaultData,
    href: '',
    rowId: 0,
  };

  componentDidMount() {
    const {
      location: { query: { id, vipCode } },
    } = this.props;
    if (id && vipCode) this.fetchDataInfo(id, vipCode);
  }

  componentDidUpdate(props: any) {
    const {
      location: { query: { id, vipCode } },
    } = this.props;
    if (id && vipCode
       && (id !== props.location.query.id || vipCode !== props.location.query.vipCode)
    ) { this.fetchDataInfo(id, vipCode); }
  }

  fetchDataInfo = (id: number, vipCode: string) => {
    const {
      pageIndex,
      pageSize,
      startDate,
      endDate,
    } = this.state;
    this.fetchAction('fetch', { id, loadUser: 1 });

    const params = {
      vipCode,
      pageIndex,
      pageSize,
      startDate: moment(startDate).format('YYYY-MM-DD'),
      endDate: moment(endDate).format('YYYY-MM-DD'),
    };
    this.fetchAction('fetchCountList', params);

    this.setState({
      href: `/thanos/vip/exportExcel?vipCode=${params.vipCode}
      &startDate=${params.startDate}&endDate=${params.endDate}`,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { startDate, endDate } = this.state;
    const { location: { query: { vipCode } } } = this.props;

    this.setState({ pageIndex, pageSize }, () => {
      const params = {
        vipCode,
        pageIndex,
        pageSize,
        startDate: moment(startDate).format('YYYY-MM-DD'),
        endDate: moment(endDate).format('YYYY-MM-DD'),
      };
      this.fetchAction('fetchCountList', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `VIPUserManagementCount/${typeName}`,
      payload,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors: any, values: any) => {
      if (errors) return;

      const rangeValue = values['range-picker'];
      const { location: { query: { vipCode } } } = this.props;
      const startDate = rangeValue ? rangeValue[0].format('YYYY-MM-DD') : '';
      const endDate = rangeValue ? rangeValue[1].format('YYYY-MM-DD') : '';
      const params = {
        ...values,
        vipCode,
        pageIndex: 1,
        pageSize: 20,
        startDate,
        endDate,
      };
      delete params['range-picker'];

      this.setState(
        {
          startDate,
          endDate,
          href: ` /thanos/vip/exportExcel?vipCode=${vipCode}&startDate=${startDate}&endDate=${endDate}`,
        }, () => this.fetchAction('fetchCountList', params),
      );
    });
  };

  handleShowDetail = (detailVisible: boolean, record?: TableListItem) => {
    this.setState({ detailVisible });

    const {
      location: { query: { vipCode } },
    } = this.props;
    const params = {
      vipCode,
      startDate: record && record.date,
    };
    this.fetchAction('fetchCountDetail', params);
  };

  handlePrint = () => {
    printJS({
      printable: 'billDetails',
      type: 'html',
      targetStyles: ['*'],
      onPrintDialogClose: () => '关闭',
      onError: error => error,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const {
      pageIndex,
      pageSize,
      detailVisible,
      startDate,
      endDate,
      href,
    } = this.state;

    const {
      detailInfo,
      dataInfo,
      loading,
      location: { query },
      detailCountInfo,
      form: { getFieldDecorator },
    }: any = this.props;

    const dataSource = dataInfo;
    const pagination: object = dataInfo
      ? {
        total: dataInfo.length,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.length}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="">
          <Descriptions bordered size="small">
            <Item label="商户名称">{detailInfo.name}</Item>
            <Item label="VIP编号">{detailInfo.vipCode}</Item>
            <Item label="商户ID">{detailInfo.id}</Item>
            <Item label="地址信息">
              {getAddressNameByCode({
                pareaCode: detailInfo.pareaCode,
                caredCode: detailInfo.careaCode,
                dareaCode: detailInfo.dareaCode,
              })}
              {detailInfo.address}
            </Item>
            <Item label=" 联系人">{detailInfo.contact}</Item>
            <Item label="手机号">{detailInfo.phone}</Item>
          </Descriptions>
        </Card>

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={10} sm={24}>
                <Form.Item label="起止日期">
                  {getFieldDecorator('range-picker', {
                    initialValue: [
                      moment(defaultData, 'YYYY/MM/DD'),
                      moment(defaultData, 'YYYY/MM/DD'),
                    ],
                  })(<RangePicker
                    disabledDate={timeLimit}
                    allowClear={false}
                    style={{ width: '100%' }}
                  />)}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Button
                  type="primary"
                  className="smallButton"
                  onClick={this.handleSearch}
                >
                  查询
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
              onClick={this.handlePrint}
            >
              打印
            </Button>
            <Button
              type="primary"
              size="small"
              className="smallButton marginR16"
            >
              <a href={href}>导出明细</a>
            </Button>
          </div>
          <Table
            className="statementTable tableHeight60"
            rowKey="date"
            tableLayout="fixed"
            loading={loading}
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
          <CountDetail
            detailVisible={detailVisible}
            lookupDetailList={detailCountInfo}
            vipCode={query.vipCode}
            handleCancel={this.handleShowDetail.bind(this)}
          />
          <PrintCount
            lookupList={dataInfo}
            detailInfo={detailInfo}
            startDate={startDate}
            endDate={endDate}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<CountProps>()(CountElem);
